package com.example.teacher_app.vm.teachermine;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.teacher_app.BuildConfig;
import com.example.teacher_app.R;
import com.example.teacher_app.bean.Data;
import com.example.teacher_app.bean.TeacherBean;
import com.example.teacher_app.data.TeacherData;
import com.example.teacher_app.databinding.TeacherMineFragmentBinding;
import com.example.teacher_app.tch_activity.setting.SettingActivity;
import com.example.teacher_app.tch_activity.tchInfomation.TchInfoActivity;
import com.example.teacher_app.tch_activity.tch_campus.CampusCardActivity;
import com.example.teacher_app.util.HttpUtil;
import com.example.teacher_app.vm.base.BaseFragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import static android.app.Activity.RESULT_OK;


public class TeacherMineFragment extends BaseFragment<TeacherMineFragmentBinding,TeacherMineViewModel> {

    public static TeacherMineFragment newInstance() {
        return new TeacherMineFragment();
    }

    @Override
    protected TeacherMineFragmentBinding setContentView(LayoutInflater inflater, @Nullable ViewGroup container) {
        return TeacherMineFragmentBinding.inflate(inflater,container,false);
    }

    @Override
    protected TeacherMineViewModel setViewModel() {
        return  ViewModelProviders.of(this).get(TeacherMineViewModel.class);
    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onFirstLoad() {
        initStudentMessage();
        binding.set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), SettingActivity.class));
            }
        });
        binding.teacherInformation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), TchInfoActivity.class));
            }
        });
        binding.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showListDialog();
            }
        });
        binding.campusCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), CampusCardActivity.class));
            }
        });
    }

    private void initStudentMessage() {
        TeacherBean teacherBean = TeacherData.TeacherBean;
        if (teacherBean == null) return;
        binding.name.setText(teacherBean.getData().get(0).getTchName());
        binding.acountNumber.setText(String.valueOf(teacherBean.getData().get(0).getTchNum()));
        binding.authentication1.setText(teacherBean.getData().get(0).getTchSystem());
        binding.authentication2.setText(teacherBean.getData().get(0).getTchTitle());
        mViewModel.path = teacherBean.getData().get(0).getTchPhoto();
        Glide.with(requireActivity()).load(mViewModel.path).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(binding.image);
    }

    private void showListDialog() {
        final String[] items = {"查看大图", "修改头像"};
        AlertDialog.Builder listDialog = new AlertDialog.Builder(requireActivity());
        listDialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        showPicDialog();
                        break;
                    case 1:
                        initPermissions();
                        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 1);
                        break;
                }
            }
        });
        listDialog.show();
    }

    private void showPicDialog() {
        Dialog dia = new Dialog(requireActivity(), R.style.dialogWindowAnim);
        dia.setContentView(R.layout.imagedialogview);
        ImageView imageView = dia.findViewById(R.id.imageview_head_big);
        Glide.with(requireActivity()).load(mViewModel.path).into(imageView);
        dia.setCanceledOnTouchOutside(true);
        Window w = dia.getWindow();
        WindowManager.LayoutParams lp = w.getAttributes();
        lp.x = 0;
        lp.y = 40;
        dia.onWindowAttributesChanged(lp);
        imageView.setOnClickListener(view -> dia.dismiss());
        dia.show();
    }

    /**
     * 请求权限
     */
    private void initPermissions() {
        mViewModel.permissionsList.clear();

        //判断哪些权限未授予
        for (String permission : mViewModel.permissions) {
            if (ActivityCompat.checkSelfPermission(requireContext(), permission) != PackageManager.PERMISSION_GRANTED) {
                mViewModel.permissionsList.add(permission);
            }
        }

        //请求权限
        if (!mViewModel.permissionsList.isEmpty()) {
            String[] permissions = mViewModel.permissionsList.toArray(new String[0]);//将List转为数组
            ActivityCompat.requestPermissions(requireActivity(), permissions, 1);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String picturePath;
        if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = requireActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();
            if (!picturePath.isEmpty()) {
                upDataFacePic(picturePath);
            }
        }
    }


    private void upDataFacePic(String imagePath) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("tchNum", TeacherData.TchNum);
        map.put("files", new File(imagePath));
        HttpUtil.httpPost(BuildConfig.SAVE_TCH_PHOTO, map, HttpUtil.ContentType.IMAGE, new HttpUtil.CallBack() {
            @Override
            public void success(HttpUtil.Result result) {
                if (result.code == 200){
                    mViewModel.path = imagePath;
                    Glide.with(requireActivity()).load(imagePath).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(binding.image);
                }else {
                    try {
                        JSONObject jsonObject = new JSONObject(result.content);
                        String message = jsonObject.getString("message");
                        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failed(IOException e) {
                Toast.makeText(requireContext(), "头像上传失败，请检查网络连接！", Toast.LENGTH_SHORT).show();
            }
        });
    }
}